package club.jdiy.admin.dao.impl;

import club.jdiy.core.base.JDiyBaseDao;
import club.jdiy.admin.entity.Guid;

public class GuidDaoImpl extends JDiyBaseDao<Guid,String> {

    public long getNo(String s) {
        return getNo(s, 1, 1);
    }

    public String getNo(String s, int len)  {
        return toStr(getNo(s), len);
    }


    private long getNo(String s, int stepNum, int beginNum){
        Guid g = this.findById(s).orElse(null);
        if (g == null) {
            g = new Guid();
            g.setId(s);
            g.setNum(beginNum);
            save(g);
            return beginNum;
        } else {
            entityManager.createQuery("update Guid o set o.num=o.num+"+stepNum+" where o.id=:prefix")
                    .setParameter("prefix",s)
                    .executeUpdate();
            entityManager.refresh(g);
            return g.getNum();
        }
    }


    private String toStr(long num, int len) {
        String s = ""+num;
        while(len>s.length()){
            s="0"+s;
        }
        return s;
    }
}